package cn.wolfcode.trip.api.controller.socket;

import cn.wolfcode.trip.base.domain.Message;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IChatRoomService;
import cn.wolfcode.trip.base.service.IMessageService;
import cn.wolfcode.trip.base.service.IUserChatRoomService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * WebSocketServiceImpl class
 *
 * @author lishuanwang
 * @date 2019/5/31
 */
@Service
public class WebSocketService {
    private Logger logger = LoggerFactory.getLogger(WebSocketService.class);
    //声明websocket连接类
    private Websocket websocket = new Websocket();
    @Autowired
    private IMessageService messageService;
    @Autowired
    private IChatRoomService chatRoomService;
    @Autowired
    private IUserChatRoomService userChatRoomService;

    private Boolean sendToUserAllTerminal(Long userId, Long receiverId, String message, Long type){
        logger.debug("向用户{}的消息：{}",receiverId,message);
        Message msg = new Message();
        if (type == 1){
            msg.setType(1);
        }
        User user = new User();
        user.setId(userId);
        msg.setAuthor(user);
        System.out.println(msg);
        User receiver = new User();
        receiver.setId(receiverId);
        msg.setReceiver(receiver);
        msg.setContent(message);
        if(websocket.sendMessage(receiverId,message)){
            msg.setReadTime(new Date());
            msg.setIsRead(true);
            messageService.save(msg);
            return true;
        }else{
            messageService.save(msg);
            return false;
        }
    }

    /**
     * @Title: sendToAllTerminal
     * @Description: 调用websocket类给用户下的所有终端发送消息
     * @param @param userId 用户id
     * @param @param message 消息
     * @param @return 发送成功返回true，否则返回false
     */
    public Boolean sendToAllTerminal(Long userId, Long receiverId, String message, Long type) {
       return  sendToUserAllTerminal(userId, receiverId, message, type);
    }

    /**
     * 检测用户是否在线
     * 传入userId,然后使用socket去检测
     */
    public Boolean checkUserStatus(Long userId){
        return websocket.checkUserStatus(userId);
    }

    /**
     * 1. 这是是通过群组发消息.
     * @param groupId
     * @param message
     * @return
     */
    public boolean sendToGroup(Long userId, Long groupId, String message) {
        List<Long> receiverIds = userChatRoomService.listUserIdByChatRoomId(groupId);
        System.out.println(receiverIds);
        Iterator<Long> iterator = receiverIds.iterator();
        while (iterator.hasNext()){
            if (iterator.next().equals(userId)){
                iterator.remove();
            }
        }
        System.out.println(receiverIds);
        try{
            for (Long receiverId: receiverIds) {
                sendToUserAllTerminal(userId, receiverId, message, 1L);
            }
            return true;
        }catch (Exception e){
            return false;
        }
    }
}
